/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.mfpms.controller;

import com.xnck.mfpms.annotation.Permission;
import com.xnck.mfpms.entity.QueryPart;
import com.xnck.mfpms.entity.RoleInfo;
import com.xnck.mfpms.entity.RuleInfo;
import com.xnck.mfpms.entity.UserInfo;
import com.xnck.mfpms.exception.ValidateException;
import com.xnck.mfpms.service.RuleService;
import com.xnck.mfpms.util.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/pms/rule")
public class SysRuleController extends BaseController{
    private static final Logger log = Logger.getLogger(SysRuleController.class);

    @Autowired
    public RuleService ruleService;

    /**
     * 规则列表
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_rule_list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView getList(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/list");
        return mv;
    }

    /**
     * 规则总数
     * @param request
     * @param response
     * @param name
     */
    @Permission("url_sys_pms_rule_list")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public void postList(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(value = "name")String name,
                         @RequestParam(value = "parentid")String parentId){
        try {
            int count = ruleService.getsCount(name, parentId);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e.toString());
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 规则主体
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_rule_listbody")
    @RequestMapping(value = "/listbody", method = RequestMethod.POST)
    public ModelAndView postBody(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "limit")int pageSize,
                                 @RequestParam(value = "offset")int beginIndex,
                                 @RequestParam(value = "name")String name,
                                 @RequestParam(value = "parentid")String parentId,
                                 @RequestParam(value = "sort", required = false)String orderName,
                                 @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/listbody");
        try {
            List<RuleInfo> rules = ruleService.gets(name, parentId, orderName, orderType, pageSize, beginIndex);
            mv.addObject("rules", rules);
        }
        catch (Exception e){
            log.error(e.toString());
        }
        return mv;
    }

    /**
     * 创建
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_rule_create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView getCreate(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/create");
        return mv;
    }

    /**
     * 创建
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_rule_create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public void postCreate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "displayname")String displayName,
                           @RequestParam(value = "parentid")String parentId,
                           @RequestParam(value = "enable", required = false)boolean enable){
        try {
            String curUserId = SessionUtils.getCurrentUserId(request);
            ruleService.create(curUserId, displayName, parentId, enable);
            responseSuccessMsg(response, null, "添加成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 修改
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_rule_update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public ModelAndView getUpdate(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "id")String ruleId){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/update");
        try {
            RuleInfo rule = ruleService.get(ruleId);
            mv.addObject("rule", rule);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 修改
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_rule_update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public void postUpdate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "id")String ruleId,
                           @RequestParam(value = "displayname")String displayName,
                           @RequestParam(value = "parentid")String parentId,
                           @RequestParam(value = "enable", required = false)boolean enable){
        try {
            ruleService.update(ruleId, displayName, parentId, enable);
            responseSuccessMsg(response, null, "修改成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 批量删除
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_rule_multidel")
    @RequestMapping(value = "/multidel", method = RequestMethod.POST)
    public void postMulti(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(value = "ids")String ruleIds){
        try {
            ruleService.deletes(ruleIds);
            responseSuccessMsg(response, null, "删除成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 规则树子节点
     * @param request
     * @param response
     * @param parentId
     */
    @Permission("url_sys_pms_rule_childs")
    @RequestMapping(value="/childs", method= RequestMethod.POST)
    public void postChilds(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value="id", required=false)String parentId){
        List<Map<String, Object>> chlids = new ArrayList<Map<String, Object>>();
        try {
            chlids = ruleService.getNodesByParentId(parentId);
        } catch (Exception e) {
            log.error(e.toString());
        }
        this.responseSuccessMsg(response, chlids, "ok");
    }

    /**
     * 规则树所有节点
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_rule_allchilds")
    @RequestMapping(value="/allchilds", method= RequestMethod.POST)
    public void postAllChilds(HttpServletRequest request, HttpServletResponse response){
        List<Map<String, Object>> chlids = new ArrayList<Map<String, Object>>();
        try {
            chlids = ruleService.getAllNodes();
        } catch (Exception e) {
            log.error(e.toString());
        }
        this.responseSuccessMsg(response, chlids, "ok");
    }

    /**
     * 设置角色
     */
    @Permission("url_sys_pms_rule_setrole")
    @RequestMapping(value = "/setrole", method = RequestMethod.GET)
    public ModelAndView getSetRole(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String ruleId){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/setrole");
        try {
            RuleInfo rule = ruleService.get(ruleId);
            mv.addObject("rule", rule);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置角色
     */
    @Permission("url_sys_pms_rule_setrole")
    @RequestMapping(value = "/setrole", method = RequestMethod.POST)
    public void postSetRole(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "rid")String ruleId,
                            @RequestParam(value = "selflag", required = false)boolean isJoin,
                            @RequestParam(value = "ids")String roleIdStr){
        try {
            if (isJoin){
                ruleService.cancelJoinRole(ruleId, roleIdStr);
            }
            else {
                ruleService.joinRole(ruleId, roleIdStr);
            }
            responseSuccessMsg(response, null, "操作成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 角色列表总数
     */
    @Permission("url_sys_pms_rule_rolelistcount")
    @RequestMapping(value = "/rolelistcount", method = RequestMethod.POST)
    public void postRoleList(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(value = "selflag", required = false)boolean isJoin,
                             @RequestParam(value = "name")String roleName,
                             @RequestParam(value = "rid")String ruleId){
        try {
            int count;
            if (isJoin){
                count = ruleService.getJoinedRolesCount(ruleId, roleName);
            }
            else {
                count = ruleService.getNoJoinRolesCount(ruleId, roleName);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 角色列表主体
     */
    @Permission("url_sys_pms_rule_rolelistbody")
    @RequestMapping(value = "/rolelistbody", method = RequestMethod.POST)
    public ModelAndView postRoleListBody(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(value = "selflag", required = false)boolean isJoin,
                                         @RequestParam(value = "name")String roleName,
                                         @RequestParam(value = "rid")String ruleId,
                                         @RequestParam(value = "limit")int pageSize,
                                         @RequestParam(value = "offset")int beginIndex,
                                         @RequestParam(value = "sort", required = false)String orderName,
                                         @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/rolelistbody");
        try {
            List<RoleInfo> roles;
            if (isJoin){
                roles = ruleService.getJoinedRoles(ruleId, roleName,
                        orderName, orderType, pageSize, beginIndex);
            }
            else {
                roles = ruleService.getNoJoinRoles(ruleId, roleName,
                        orderName, orderType, pageSize, beginIndex);
            }

            mv.addObject("roles", roles);
            mv.addObject("selflag", isJoin);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置人员
     */
    @Permission("url_sys_pms_rule_setuser")
    @RequestMapping(value = "/setuser", method = RequestMethod.GET)
    public ModelAndView getSetUser(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String ruleId){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/setuser");
        try {
            RuleInfo rule = ruleService.get(ruleId);
            mv.addObject("rule", rule);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置人员
     */
    @Permission("url_sys_pms_rule_setuser")
    @RequestMapping(value = "/setuser", method = RequestMethod.POST)
    public void postSetUser(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "rid")String ruleId,
                            @RequestParam(value = "selflag", required = false)boolean isJoin,
                            @RequestParam(value = "ids")String userIdStr){
        try {
            if (isJoin){
                ruleService.cancelJoinUser(ruleId, userIdStr);
            }
            else {
                ruleService.joinUser(ruleId, userIdStr);
            }
            responseSuccessMsg(response, null, "操作成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 人员列表总数
     */
    @Permission("url_sys_pms_rule_userlistcount")
    @RequestMapping(value = "/userlistcount", method = RequestMethod.POST)
    public void postUserListCount(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "selflag", required = false)boolean isJoin,
                                  @RequestParam(value = "name")String userName,
                                  @RequestParam(value = "rid")String ruleId){
        try {
            int count;
            if (isJoin){
                count = ruleService.getJoinedUsersCount(ruleId, userName);
            }
            else {
                count = ruleService.getNoJoinUsersCount(ruleId, userName);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 人员列表主体
     */
    @Permission("url_sys_pms_rule_userlistbody")
    @RequestMapping(value = "/userlistbody", method = RequestMethod.POST)
    public ModelAndView postUserListBody(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(value = "selflag", required = false)boolean isJoin,
                                         @RequestParam(value = "name")String userName,
                                         @RequestParam(value = "rid")String ruleId,
                                         @RequestParam(value = "limit")int pageSize,
                                         @RequestParam(value = "offset")int beginIndex,
                                         @RequestParam(value = "sort", required = false)String orderName,
                                         @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/role/userlistbody");
        try {
            List<UserInfo> users;
            if (isJoin){
                users = ruleService.getJoinedUsers(ruleId, userName,
                        orderName, orderType, pageSize, beginIndex);
            }
            else {
                users = ruleService.getNoJoinUsers(ruleId, userName,
                        orderName, orderType, pageSize, beginIndex);
            }

            mv.addObject("users", users);
            mv.addObject("selflag", isJoin);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置数据资源
     */
    @Permission("url_sys_pms_rule_setqpart")
    @RequestMapping(value = "/setqpart", method = RequestMethod.GET)
    public ModelAndView getSetRes(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "id")String ruleId){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/setqpart");
        try {
            RuleInfo rule = ruleService.get(ruleId);
            mv.addObject("rule", rule);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置数据资源
     */
    @Permission("url_sys_pms_rule_setqpart")
    @RequestMapping(value = "/setqpart", method = RequestMethod.POST)
    public void postSetRes(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "id")String ruleId,
                           @RequestParam(value = "selflag", required = false)boolean isJoin,
                           @RequestParam(value = "ids")String qpartIdStr){
        try {
            if (isJoin){
                ruleService.cancelJoinQPart(ruleId, qpartIdStr);
            }
            else {
                ruleService.joinQPart(ruleId, qpartIdStr);
            }
            responseSuccessMsg(response, null, "操作成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 数据资源列表总数
     */
    @Permission("url_sys_pms_rule_qpartlistcount")
    @RequestMapping(value = "/qpartlistcount", method = RequestMethod.POST)
    public void postResListCount(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "selflag", required = false)boolean isJoin,
                                 @RequestParam(value = "name")String qpartName,
                                 @RequestParam(value = "id")String ruleId){
        try {
            int count;
            if (isJoin){
                count = ruleService.getJoinedQPartCount(ruleId, qpartName);
            }
            else {
                count = ruleService.getNoJoinQPartCount(ruleId, qpartName);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 数据资源列表主体
     */
    @Permission("url_sys_pms_rule_qpartlistbody")
    @RequestMapping(value = "/qpartlistbody", method = RequestMethod.POST)
    public ModelAndView postResListBody(HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam(value = "selflag", required = false)boolean isJoin,
                                        @RequestParam(value = "name")String qpartName,
                                        @RequestParam(value = "id")String ruleId,
                                        @RequestParam(value = "limit")int pageSize,
                                        @RequestParam(value = "offset")int beginIndex,
                                        @RequestParam(value = "sort", required = false)String orderName,
                                        @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/rule/qpartlistbody");
        try {
            List<QueryPart> queryParts;
            if (isJoin){
                queryParts = ruleService.getJoinedQPart(ruleId, qpartName,
                        orderName, orderType, pageSize, beginIndex);
            }
            else {
                queryParts = ruleService.getNoJoinQPart(ruleId, qpartName,
                        orderName, orderType, pageSize, beginIndex);
            }

            mv.addObject("parts", queryParts);
            mv.addObject("selflag", isJoin);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }
}
